package com.zzxx.photograph.dao.impl;

import com.zzxx.photograph.dao.FavoriteDao;
import com.zzxx.photograph.domain.FavoriteNum;
import com.zzxx.photograph.util.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class FavoriteDaoImpl implements FavoriteDao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    @Override
    public int findCountByIidAndUid(int iid, int uid) {
        String sql = "select count(*) from favorite where iid = ? and uid = ?";
        return template.queryForObject(sql, Integer.class, iid, uid);
    }

    @Override
    public void insert(int iid, int uid) {
        String sql = "insert into favorite values(?,?,?)";
        template.update(sql, iid, new Date(), uid);
    }

    @Override
    public void delete(int iid, int uid) {
        String sql = "delete from favorite where iid = ? and uid = ?";
        template.update(sql, iid, uid);
    }

    @Override
    public List<Integer> findIidByUid(int uid) {
        // 在favorite中通过uid查询iid
        String sql = "select iid from favorite where uid = ?";
        List<Map<String, Object>> maps = template.queryForList(sql, uid);
        List<Integer> list = new ArrayList<>();
        for (Map<String, Object> map : maps) {
            Integer iid = (Integer) map.get("iid");
            list.add(iid);
        }
        return list;
    }

    @Override
    public int favoriteCount(int iid) {
        String sql = "select count(*) from favorite where iid=?";
        return template.queryForObject(sql, Integer.class, iid);
    }

    @Override
    public int findCountByIid() {
        String sql = "select count(distinct iid) from favorite";
        return template.queryForObject(sql, Integer.class);
    }

    @Override
    public List<FavoriteNum> findIid(int start, int pageSize) {
        String sql = "SELECT a.iid ,a.num FROM (SELECT iid ,COUNT(*) AS num FROM favorite GROUP BY iid) a ORDER BY a.num desc limit ?,?;";
        return template.query(sql, new BeanPropertyRowMapper<>(FavoriteNum.class), start, pageSize);
    }

    @Override
    public void deleteFavoriteImg(Integer iid) {
        String sql = "delete from favorite where iid=?";
        template.update(sql, iid);
    }
}
